const express = require('express');
const router = express.Router();
const { Op, Sequelize } = require('sequelize');
const PointsService = require('../services/pointsService');
const { PointsTransaction, User } = require('../models');
const auth = require('../middleware/auth');
const adminAuth = require('../middleware/adminAuth');

// 获取用户积分余额
router.get('/balance', auth, async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id, { attributes: ['points'] });
    
    res.json({
      success: true,
      data: {
        points: user.points,
        availablePoints: user.points
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取积分余额失败',
      error: error.message
    });
  }
});

// 获取积分交易记录
router.get('/transactions', auth, async (req, res) => {
  try {
    const { type, source, page, limit, startDate, endDate } = req.query;
    
    const result = await PointsService.getTransactions(req.user.id, {
      type,
      source,
      page,
      limit,
      startDate,
      endDate
    });
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取积分记录失败',
      error: error.message
    });
  }
});

// 获取积分历史记录（别名，与transactions相同）
router.get('/history', auth, async (req, res) => {
  try {
    const { type, source, page = 1, limit = 20, startDate, endDate } = req.query;
    
    const result = await PointsService.getTransactions(req.user.id, {
      type,
      source,
      page,
      limit,
      startDate,
      endDate
    });
    
    res.json({
      success: true,
      data: {
        records: result.transactions || [],
        totalPages: result.pagination?.total || 1,
        currentPage: parseInt(page),
        totalItems: result.pagination?.totalItems || 0
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取积分记录失败',
      error: error.message
    });
  }
});

// 获取积分统计
router.get('/stats', auth, async (req, res) => {
  try {
    const stats = await PointsService.getPointsStats(req.user.id);
    
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取积分统计失败',
      error: error.message
    });
  }
});

// 每日签到
router.post('/checkin', auth, async (req, res) => {
  try {
    const result = await PointsService.dailyCheckin(req.user.id);
    
    res.json({
      success: true,
      message: '签到成功',
      data: {
        rewardPoints: result.rewardPoints,
        consecutiveDays: result.consecutiveDays,
        newBalance: result.newBalance
      }
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

// 检查签到状态
router.get('/checkin/status', auth, async (req, res) => {
  try {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    let todayTransaction;
    try {
      todayTransaction = await PointsTransaction.findOne({
        where: {
          userId: req.user.id,
          source: 'activity',
          description: { [Op.like]: '%签到%' },
          created_at: { [Op.gte]: today }
        }
      });
    } catch (error) {
      // 如果 createdAt 字段不存在，查询最近的签到记录
      todayTransaction = await PointsTransaction.findOne({
        where: {
          userId: req.user.id,
          source: 'activity',
          description: { [Op.like]: '%签到%' }
        },
        order: [['id', 'DESC']]
      });
    }
    
    // 获取连续签到天数
    let consecutiveDays = 0;
    if (todayTransaction) {
      const match = todayTransaction.description.match(/连续(\d+)天/);
      consecutiveDays = match ? parseInt(match[1]) : 1;
    } else {
      // 检查昨天是否签到
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      let yesterdayTransaction;
      try {
        yesterdayTransaction = await PointsTransaction.findOne({
          where: {
            userId: req.user.id,
            source: 'activity',
            description: { [Op.like]: '%签到%' },
            created_at: { 
              [Op.gte]: yesterday, 
              [Op.lt]: today 
            }
          }
        });
      } catch (error) {
        yesterdayTransaction = null;
      }
      
      if (yesterdayTransaction) {
        const match = yesterdayTransaction.description.match(/连续(\d+)天/);
        consecutiveDays = match ? parseInt(match[1]) : 1;
      }
    }
    
    res.json({
      success: true,
      data: {
        hasCheckedIn: !!todayTransaction,
        consecutiveDays,
        nextReward: consecutiveDays >= 6 ? 15 : (consecutiveDays >= 2 ? 10 : 5)
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取签到状态失败',
      error: error.message
    });
  }
});

// 管理员调整用户积分
router.post('/admin/adjust', auth, async (req, res) => {
  try {
    // 检查管理员权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，需要管理员权限'
      });
    }

    const { userId, amount, description } = req.body;
    
    if (!userId || amount === undefined || !description) {
      return res.status(400).json({
        success: false,
        message: '参数不完整'
      });
    }
    
    const result = await PointsService.adjustPoints(
      userId,
      parseInt(amount),
      req.user.id,
      description
    );
    
    res.json({
      success: true,
      message: '积分调整成功',
      data: {
        newBalance: result.newBalance,
        amount: parseInt(amount)
      }
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

// 用户消费积分（商品兑换、打印服务等）
router.post('/consume', auth, async (req, res) => {
  try {
    const { amount, source, description, orderId } = req.body;
    
    if (!amount || amount <= 0) {
      return res.status(400).json({
        success: false,
        message: '消费金额必须大于0'
      });
    }
    
    if (!source || !description) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    const result = await PointsService.deductPoints(
      req.user.id,
      parseInt(amount),
      source,
      description,
      { orderId }
    );
    
    res.json({
      success: true,
      message: '积分消费成功',
      data: {
        newBalance: result.newBalance,
        amount: parseInt(amount)
      }
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

// 用户获得积分（任务完成、活动奖励等）
router.post('/earn', auth, async (req, res) => {
  try {
    const { amount, source, description } = req.body;
    
    if (!amount || amount <= 0) {
      return res.status(400).json({
        success: false,
        message: '奖励金额必须大于0'
      });
    }
    
    if (!source || !description) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    const result = await PointsService.addPoints(
      req.user.id,
      parseInt(amount),
      source,
      description
    );
    
    res.json({
      success: true,
      message: '积分获得成功',
      data: {
        newBalance: result.newBalance,
        amount: parseInt(amount)
      }
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

// 获取所有用户积分交易记录（管理员）
router.get('/admin/transactions', auth, adminAuth, async (req, res) => {
  try {
    const {
      userId,
      type,
      source,
      page = 1,
      limit = 20,
      startDate,
      endDate
    } = req.query;
    
    const where = {};
    
    if (userId) {
      where.userId = userId;
    }
    
    if (type) {
      where.type = type;
    }
    
    if (source) {
      where.source = source;
    }
    
    if (startDate || endDate) {
      try {
        where.created_at = {};
        if (startDate) {
          where.created_at[Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.created_at[Op.lte] = new Date(endDate);
        }
      } catch (error) {
        // 如果 created_at 字段不存在，忽略时间过滤
        console.warn('created_at 字段不存在，忽略时间过滤');
      }
    }
    
    const { count: total, rows: transactions } = await PointsTransaction.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['phone', 'nickname'],
          required: false
        },
        {
          model: User,
          as: 'relatedUser',
          attributes: ['nickname'],
          required: false
        }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });
    
    res.json({
      success: true,
      data: {
        transactions,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(total / limit),
          pageSize: parseInt(limit),
          totalItems: total
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取积分记录失败',
      error: error.message
    });
  }
});

// 观看广告获得积分
router.post('/watch-ad', auth, async (req, res) => {
  try {
    const userId = req.user.id;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    // 检查今日观看次数
    let todayWatchCount = 0;
    try {
      todayWatchCount = await PointsTransaction.count({
        where: {
          userId,
          source: 'ad_watch',
          created_at: { [Op.gte]: today, [Op.lt]: tomorrow }
        }
      });
    } catch (error) {
      // 如果 createdAt 字段不存在，暂时允许观看
      todayWatchCount = 0;
    }
    
    if (todayWatchCount >= 20) {
      return res.status(400).json({
        success: false,
        message: '今日观看次数已达上限'
      });
    }
    
    // 添加积分
    const rewardPoints = 5;
    const result = await PointsService.addPoints(userId, rewardPoints, 'ad_watch', '观看广告奖励');
    
    res.json({
      success: true,
      message: '观看广告完成',
      data: {
        rewardPoints,
        newBalance: result.newBalance,
        todayWatchCount: todayWatchCount + 1
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '观看广告失败',
      error: error.message
    });
  }
});

// 积分转账
router.post('/transfer', auth, async (req, res) => {
  try {
    const { toUserId, amount, description } = req.body;
    
    if (!toUserId || !amount || amount <= 0) {
      return res.status(400).json({
        success: false,
        message: '参数不完整或无效'
      });
    }
    
    const result = await PointsService.transferPoints(
      req.user.id,
      parseInt(toUserId),
      parseInt(amount),
      description || '积分转账'
    );
    
    res.json({
      success: true,
      message: '积分转账成功',
      data: {
        fromBalance: result.fromUser.newBalance,
        toBalance: result.toUser.newBalance,
        amount: parseInt(amount)
      }
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

// 获取积分系统统计（管理员）
router.get('/admin/stats', auth, async (req, res) => {
  try {
    // 检查管理员权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，需要管理员权限'
      });
    }
    const { startDate, endDate } = req.query;
    const dateWhere = {};
    
    if (startDate || endDate) {
      try {
        dateWhere.created_at = {};
        if (startDate) {
          dateWhere.created_at[Op.gte] = new Date(startDate);
        }
        if (endDate) {
          dateWhere.created_at[Op.lte] = new Date(endDate);
        }
      } catch (error) {
        // 如果 created_at 字段不存在，忽略时间过滤
        console.warn('created_at 字段不存在，忽略时间过滤');
      }
    }
    
    const [
      totalPointsIssued,
      totalPointsSpent,
      totalTransactions,
      activeUsers,
      topUsers
    ] = await Promise.all([
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('amount')), 'total']],
        where: { ...dateWhere, type: 'earn' },
        raw: true
      }).then(result => result?.total || 0),
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.fn('ABS', Sequelize.col('amount'))), 'total']],
        where: { ...dateWhere, type: 'spend' },
        raw: true
      }).then(result => result?.total || 0),
      PointsTransaction.count({ where: dateWhere }),
      PointsTransaction.findAll({
        attributes: [[Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('userId'))), 'count']],
        where: dateWhere,
        raw: true
      }).then(result => result[0]?.count || 0),
      User.findAll({
        where: { points: { [Op.gt]: 0 } },
        attributes: ['nickname', 'points'],
        order: [['points', 'DESC']],
        limit: 10
      })
    ]);
    
    res.json({
      success: true,
      data: {
        totalPointsIssued,
        totalPointsSpent,
        totalTransactions,
        activeUsers,
        topUsers
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: error.message
    });
  }
});

module.exports = router;